import { createRouter, createWebHashHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue'),
    meta: {
      title: '登录 - 景点标注系统',
      requiresAuth: false,
      layout: 'blank' // 使用空白布局
    }
  },
  {
    path: '/',
    redirect: '/annotation-editor'
  },
  {
    path: '/annotation-editor',
    name: 'annotation-editor',
    component: () => import(/* webpackChunkName: "annotation-editor" */ '../views/AnnotationEditor.vue'),
    meta: {
      title: '景点标注系统',
      requiresAuth: true
    }
  },
  {
    path: '/annotation-viewer',
    name: 'annotation-viewer',
    component: () => import(/* webpackChunkName: "annotation-viewer" */ '../views/AnnotationViewer.vue'),
    meta: {
      title: '预览模式 - 景点标注系统',
      requiresAuth: true
    }
  },
  {
    path: '/annotation-editorMobile',
    name: 'annotation-editorMobile',
    component: () => import(/* webpackChunkName: "annotation-mobile" */ '../views/AnnotationEditorMobile.vue'),
    meta: {
      title: '移动端编辑 - 景点标注系统',
      requiresAuth: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/annotation-editor'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  }

  // 检查是否需要登录验证
  if (to.meta && to.meta.requiresAuth) {
    const isLoggedIn = sessionStorage.getItem('isLoggedIn')
    const userInfo = sessionStorage.getItem('userInfo')

    if (isLoggedIn === 'true' && userInfo) {
      // 已登录，允许访问
      next()
    } else {
      // 未登录，跳转到登录页
      ElMessage.warning('请先登录')
      next('/login')
    }
  } else {
    // 不需要登录验证的页面
    if (to.path === '/login') {
      // 如果已经登录，访问登录页时跳转到首页
      const isLoggedIn = sessionStorage.getItem('isLoggedIn')
      if (isLoggedIn === 'true') {
        next('/annotation-editor')
        return
      }
    }
    next()
  }
})

export default router
